import { ref, reactive } from 'vue'

// 全局模态框状态
const modalState = reactive({
  visible: false,
  title: '',
  message: '',
  type: 'default',
  confirmText: '确认',
  cancelText: '取消',
  showClose: true,
  showCancel: true,
  showConfirm: true,
  closeOnOverlay: true,
  onConfirm: null,
  onCancel: null,
  onClose: null
})

// 显示模态框
export const showModal = (options = {}) => {
  Object.assign(modalState, {
    visible: true,
    title: options.title || '',
    message: options.message || '',
    type: options.type || 'default',
    confirmText: options.confirmText || '确认',
    cancelText: options.cancelText || '取消',
    showClose: options.showClose !== false,
    showCancel: options.showCancel !== false,
    showConfirm: options.showConfirm !== false,
    closeOnOverlay: options.closeOnOverlay !== false,
    onConfirm: options.onConfirm || null,
    onCancel: options.onCancel || null,
    onClose: options.onClose || null
  })
}

// 隐藏模态框
export const hideModal = () => {
  modalState.visible = false
  modalState.onClose?.()
}

// 显示确认对话框
export const showConfirm = (options = {}) => {
  return new Promise((resolve) => {
    showModal({
      ...options,
      type: options.type || 'default',
      showCancel: true,
      onConfirm: () => {
        hideModal()
        resolve(true)
      },
      onCancel: () => {
        hideModal()
        resolve(false)
      }
    })
  })
}

// 显示警告对话框
export const showWarning = (options = {}) => {
  return showConfirm({
    ...options,
    type: 'warning'
  })
}

// 显示错误对话框
export const showError = (options = {}) => {
  return showConfirm({
    ...options,
    type: 'danger'
  })
}

// 显示信息对话框
export const showInfo = (options = {}) => {
  return showConfirm({
    ...options,
    type: 'info'
  })
}

// 获取模态框状态
export const useModal = () => {
  return {
    modalState,
    showModal,
    hideModal,
    showConfirm,
    showWarning,
    showError,
    showInfo
  }
}